package com.xxxx.manager.controller;

import com.xxxx.api.service.SSOService;
import com.xxxx.api.pojo.Admin;
import com.xxxx.api.utils.CookieUtil;
import com.xxxx.api.utils.RespBean;
import com.xxxx.api.utils.UserIDBase64;
import com.xxxx.manager.service.CookieService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author : ymd
 * @Date : 2020/11/2 0002 16:00
 * @Version 1.0
 * @Description : 用户控制层
 */
@Controller
@RequestMapping("/user")
public class UserControl {
    @Reference(version = "1.0")
    private SSOService ssoService;
    @Resource
    private CookieService cookieService;

    @ResponseBody
    @RequestMapping("/login")
    public RespBean login (Admin admin,String verify, HttpServletRequest request, HttpServletResponse response){
        //生成信息
        String ticket = ssoService.Login(admin);
        //将验证码放入session中
        String captcha=(String)request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(verify.trim())||!captcha.equals(verify.trim())){
            return RespBean.error("验证码错误！");
        }
        //如果有信息
        if (!StringUtils.isEmpty(ticket)){
            boolean result = cookieService.setCookie(request, response, ticket);
            request.getSession().setAttribute("user", admin);
            //设置用户id的cookie
            String id = ssoService.queryByName(admin.getUserName()).getAdminId().toString();
            int i = Integer.parseInt(id);
            String s = UserIDBase64.encoderUserID(i);
            CookieUtil.setCookieNoEncode("userId", s, "", response);
            return result?RespBean.success("登陆成功！"):RespBean.error("登录失败！");
        }
        return RespBean.error("登录失败！");
    }

    @GetMapping("/index")
    public String index (){
        return "index";
    }

    @RequestMapping("/logout")
    public String logout (HttpServletRequest request,HttpServletResponse response){
        String ticket = cookieService.getCookie(request);
        ssoService.logout(ticket);
        request.getSession().removeAttribute("user");
        cookieService.deleteCookie(request, response);
        return "login";
    }

    /**
     * 首页接口
     * @return
     */
    @RequestMapping("/welcome")
    public String welcome (){
        return "welcome";
    }
}
